import axios from 'axios';

// 获取分类列表的函数
// 获取分类列表的函数
export const fetchCategories = async () => {
  try {
    const response = await axios.get('http://192.168.239.53:8082/category');
    console.log('Response:', response);
    if (response.data.code === 1) {
      return response.data.data; // 返回 data 数组
    } else {
      console.error('Unexpected response:', response.data);
      throw new Error('Failed to fetch categories');
    }
  } catch (error) {
    console.error('Error fetching categories:', error);
    throw error;
  }
};




// 根据分类ID获取分类详情
const getCategories = async () => {
  try {
    const categoriesData = await fetchCategories();
    categories.value = categoriesData.data; // 确保你提取的是 data 数组
    console.log('Categories loaded:', categories.value);
  } catch (error) {
    console.error('Error fetching categories in CategoryMenu:', error.message);
  }
};


// 创建新分类
export const createCategory = async (categoryData) => {
  try {
    const response = await axios.post('http://192.168.239.53:8082/category', categoryData);  // 确保路径与后端一致
    return response.data;
  } catch (error) {
    console.error('Error creating category:', error);
    throw error;
  }
};



// 更新分类信息
export const updateCategory = async ( categoryData) => {
  try {
    const response = await axios.put(`http://192.168.239.53:8082/category`, categoryData);  // 确保路径与后端一致
    return response.data.data;
  } catch (error) {
    console.error(`Error updating category with ID :`, error);
    throw error;
  }
};

// 删除分类
export const deleteCategory = async (categoryId) => {
  try {
    const response = await axios.delete(`http://192.168.239.53:8082/category/${categoryId}`);
    return response.data;  // 返回删除成功的响应
  } catch (error) {
    console.error(`Error deleting category with ID ${categoryId}:`, error);
    throw error;
  }
};
